<!--
 * @Author: 胡彪 675473760@qq.com
 * @Date: 2025-08-15 21:15:00
 * @LastEditors: 胡彪 675473760@qq.com
 * @LastEditTime: 2025-08-15 21:29:04
 * @FilePath: \web-cloudbase-vue-template\src\components\MonopolyGame.vue
 * @Description: 大富翁游戏主组件
-->
<template>
  <div class="monopoly-game">
    <!-- 游戏主界面 -->
    <div class="game-container">
      <!-- 顶部导航栏 -->
      <div class="game-navbar">
        <h1 class="game-title">大富翁游戏</h1>
        <div class="nav-actions">
          <button @click="openSaveLoadModal" class="nav-button">
            存档/读档
          </button>
          <button @click="openGameRecordsModal" class="nav-button">
            游戏记录
          </button>
          <CloudBaseNavLink />
        </div>
      </div>
      
      <!-- 存档/读档弹窗 -->
      <SaveLoadModal 
        v-if="showSaveLoadModal"
        :showModal="showSaveLoadModal"
        @update:showModal="showSaveLoadModal = $event"
        :gameState="gameState"
        :isLoggedIn="isLoggedIn"
        :onShowEventMessage="showEventMessage"
        :onAutoLogin="autoLogin"
        :onLoadGame="handleLoadGame"
      />
      
      <!-- 游戏记录弹窗 -->
      <div v-if="showGameRecordsModal" class="modal-overlay" @click.self="showGameRecordsModal = false">
        <div class="modal-content">
          <div class="modal-header">
            <h3>游戏记录</h3>
            <button @click="showGameRecordsModal = false" class="close-button">&times;</button>
          </div>
          
          <div class="modal-body">
            <GameRecords />
          </div>
        </div>
      </div>
      
      <!-- 游戏主界面 -->
      <div v-if="!showGameRecordsModal && !showSaveLoadModal">
        <!-- 游戏棋盘 - 包含玩家信息和骰子 -->
        <GameBoard 
          :boardCells="gameState.boardCells" 
          :players="gameState.players"
          :currentPlayerIndex="gameState.currentPlayerIndex"
          :disabled="gameState.gameEnded || gameState.showEvent"
          :isMoving="gameState.isMoving"
          @rolled="handleDiceRoll"
        />
        
        <!-- 游戏状态 -->
        <div class="game-status">
          <div class="round-info">
            回合: {{ gameState.currentRound }} / {{ gameState.maxRounds }}
          </div>
          <div v-if="gameState.gameEnded" class="game-over">
            游戏结束！
            <button @click="restartGame" class="restart-button">
              重新开始
            </button>
          </div>
        </div>
        
        <!-- 游戏事件 -->
        <GameEvents 
          :showEvent="gameState.showEvent" 
          :currentEvent="gameState.currentEvent" 
          @action="handleEventAction" 
        />
      </div>
    </div>
  </div>
</template>

<script>
import GameBoard from './GameBoard.vue';
import GameEvents from './GameEvents.vue';
import GameRecords from './GameRecords.vue';
import CloudBaseNavLink from './CloudBaseNavLink.vue';
import SaveLoadModal from './SaveLoadModal.vue';
import userService from '../services/userService';
import gameService from '../services/gameService';
import saveGameService from '../services/saveGameService';
import GameLogic from '../utils/GameLogic';
import gameStateService from '../services/gameStateService';
import gameAnimationService from '../services/gameAnimationService';
import gameInteractionService from '../services/gameInteractionService';

export default {
  name: 'MonopolyGame',
  components: {
    GameBoard,
    GameEvents,
    GameRecords,
    CloudBaseNavLink,
    SaveLoadModal
  },
  created() {
    // 组件创建时自动执行匿名登录
    this.anonymousLogin();
  },
  data() {
    // 创建初始游戏状态
    const initialState = gameStateService.createInitialState();
    
    // 立即初始化棋盘数据和机会卡数据
    initialState.boardCells = gameStateService.initBoardData();
    initialState.chanceCards = gameStateService.initChanceCards();
    
    return {
      // 用户认证相关
      isLoggedIn: false,
      
      // 弹窗控制
      showSaveLoadModal: false,
      showGameRecordsModal: false,
      
      // 交换地产时的临时数据
      exchangeTargetPlayerId: null,
      
      // 游戏状态
      gameState: initialState
    };
  },
  methods: {
    // 自动匿名登录
    async autoLogin() {
      console.log('执行自动登录');
      return this.anonymousLogin();
    },
    
    // 用户认证相关方法
    async anonymousLogin() {
      try {
        await userService.anonymousLogin();
        this.isLoggedIn = true;
      } catch (error) {
        console.error('匿名登录失败:', error);
      }
    },
    
    // 打开存档/读档弹窗
    openSaveLoadModal() {
      console.log('打开存档/读档弹窗');
      this.showSaveLoadModal = true;
    },
    
    // 打开游戏记录弹窗
    openGameRecordsModal() {
      console.log('打开游戏记录弹窗');
      this.showGameRecordsModal = true;
    },
    
    // 处理加载游戏
    handleLoadGame(gameState) {
      // 恢复游戏状态
      this.gameState.players = gameState.players;
      this.gameState.boardCells = gameState.boardCells;
      this.gameState.currentPlayerIndex = gameState.currentPlayerIndex;
      this.gameState.currentRound = gameState.currentRound;
      this.gameState.maxRounds = gameState.maxRounds;
      this.gameState.gameEnded = gameState.gameEnded;
      this.gameState.playerSpecialStatus = gameState.playerSpecialStatus;
      
      // 显示成功消息
      this.showEventMessage(
        '加载成功', 
        '游戏存档已成功加载', 
        [{ text: '继续游戏', action: 'confirm' }]
      );
    },
    
    // 处理骰子点数
    handleDiceRoll(value) {
      // 如果游戏已结束或有事件显示，则不处理骰子点数
      if (this.gameState.gameEnded || this.gameState.showEvent) return;
      
      // 移动当前玩家
      this.movePlayer(this.gameState.currentPlayerIndex, value);
    },
    
    // 移动玩家 - 带动画效果
    movePlayer(playerIndex, steps) {
      gameAnimationService.movePlayer(
        this.gameState,
        playerIndex,
        steps,
        (moveResult) => {
          // 如果经过起点，显示获得200元的消息
          if (moveResult.passedStart) {
            this.showEventMessage('经过起点', '你经过了起点，获得200元', [
              { text: '确定', action: 'confirm' }
            ]);
          }
          
          // 移动完成后处理落地事件
          this.handlePlayerLanding();
        }
      );
    },
    
    // 显示浮动文本效果
    showFloatingText(text, type = 'normal') {
      gameAnimationService.showFloatingText(text, type);
    },
    
    // 处理玩家落地事件
    handlePlayerLanding() {
      GameLogic.handlePlayerLanding(
        this.gameState, 
        this.showEventMessage, 
        this.handleBankruptcy, 
        this.nextTurn
      );
    },
    
    // 显示事件消息
    showEventMessage(title, description, actions) {
      this.gameState.currentEvent = {
        title,
        description,
        actions
      };
      this.gameState.showEvent = true;
    },
    
    // 处理事件动作
    handleEventAction(action) {
      this.gameState.showEvent = false;
      
      const callbacks = {
        showEventMessage: this.showEventMessage,
        nextTurn: this.nextTurn,
        movePlayer: this.movePlayer,
        buyProperty: this.buyProperty,
        handleBankruptcy: this.handleBankruptcy,
        initiatePropertyExchange: this.initiatePropertyExchange,
        handlePropertyExchange: this.handlePropertyExchange,
        handleSelectOwnProperty: this.handleSelectOwnProperty,
        completePropertyExchange: this.completePropertyExchange,
        autoLogin: this.autoLogin,
        showFloatingText: this.showFloatingText
      };
      
      GameLogic.handleEventAction(action, this.gameState, callbacks);
    },
    
    // 购买地产
    buyProperty(cell) {
      const player = this.gameState.players[this.gameState.currentPlayerIndex];
      
      if (player.money >= cell.price) {
        player.money -= cell.price;
        cell.owner = player.id;
        player.properties.push(cell.name);
        
        this.nextTurn();
      } else {
        // 理论上不会发生，因为之前已经检查过资金
        this.nextTurn();
      }
    },
    
    // 进入下一回合
    nextTurn() {
      // 检查当前玩家是否有额外回合
      const currentPlayer = this.gameState.players[this.gameState.currentPlayerIndex];
      if (this.gameState.playerSpecialStatus[currentPlayer.id].extraTurn) {
        // 使用额外回合
        this.gameState.playerSpecialStatus[currentPlayer.id].extraTurn = false;
        this.showEventMessage(
          '额外回合', 
          `${currentPlayer.name}使用了额外回合特权，继续行动！`, 
          [{ text: '继续', action: 'confirm' }]
        );
        return;
      }
      
      // 更新当前玩家索引
      this.gameState.currentPlayerIndex = (this.gameState.currentPlayerIndex + 1) % this.gameState.players.length;
      
      // 如果回到第一个玩家，增加回合数
      if (this.gameState.currentPlayerIndex === 0) {
        this.gameState.currentRound++;
        
        // 检查是否达到最大回合数
        if (this.gameState.currentRound > this.gameState.maxRounds) {
          this.endGame();
        }
      }
      
      // 检查游戏是否应该结束
      this.checkGameEnd();
    },
    
    // 处理破产
    handleBankruptcy(player) {
      // 移除所有地产的所有权
      this.gameState.boardCells.forEach(cell => {
        if (cell.owner === player.id) {
          cell.owner = null;
        }
      });
      
      // 重置玩家状态
      player.money = 0;
      player.properties = [];
      
      this.showEventMessage(
        '破产', 
        `${player.name}破产了！所有地产已被银行收回`, 
        [{ text: '确定', action: 'confirm' }]
      );
      
      // 检查游戏是否应该结束
      this.checkGameEnd();
    },
    
    // 初始化财产交换
    initiatePropertyExchange() {
      gameInteractionService.initiatePropertyExchange(this.gameState, this.showEventMessage);
    },
    
    // 处理财产交换
    handlePropertyExchange(targetPlayerId) {
      const result = gameInteractionService.handlePropertyExchange(
        this.gameState,
        this.gameState.currentPlayerIndex,
        targetPlayerId,
        this.showEventMessage
      );
      
      if (result.success) {
        this.exchangeTargetPlayerId = result.targetPlayerId;
      } else {
        this.nextTurn();
      }
    },
    
    // 选择自己的地产后，选择对方的地产
    handleSelectOwnProperty(cellIndex) {
      gameInteractionService.handleSelectOwnProperty(
        this.gameState,
        cellIndex,
        this.exchangeTargetPlayerId,
        this.showEventMessage
      );
    },
    
    // 完成交换
    completePropertyExchange(ownCellIndex, targetCellIndex) {
      gameInteractionService.completePropertyExchange(
        this.gameState,
        this.gameState.currentPlayerIndex,
        ownCellIndex,
        targetCellIndex,
        this.exchangeTargetPlayerId,
        this.showEventMessage
      );
    },
    
    // 检查游戏是否结束
    checkGameEnd() {
      // 检查是否只剩一个玩家没有破产
      const activePlayers = this.gameState.players.filter(p => p.money > 0);
      if (activePlayers.length <= 1 || this.gameState.currentRound > this.gameState.maxRounds) {
        this.endGame();
      }
    },
    
    // 结束游戏
    endGame() {
      this.gameState.gameEnded = true;
      
      // 找出最富有的玩家
      let winner = this.gameState.players[0];
      this.gameState.players.forEach(p => {
        if (p.money > winner.money) {
          winner = p;
        }
      });
      
      // 保存游戏记录到云数据库
      this.saveGameRecord(winner);
    },
    
    // 保存游戏记录到云数据库
    async saveGameRecord(winner) {
      if (!this.isLoggedIn) return;
      
      try {
        const gameRecord = {
          winner: winner.name,
          winnerId: winner.id,
          winnerMoney: winner.money,
          rounds: this.gameState.currentRound,
          date: new Date(),
          players: this.gameState.players.map(p => ({
            name: p.name,
            money: p.money,
            properties: p.properties.length
          }))
        };
        
        await gameService.saveGameRecord(gameRecord);
        console.log('游戏记录已保存');
      } catch (error) {
        console.error('保存游戏记录失败:', error);
      }
    },
    
    // 重新开始游戏
    restartGame() {
      // 创建新的初始游戏状态
      const initialState = gameStateService.createInitialState();
      
      // 立即初始化棋盘数据和机会卡数据
      initialState.boardCells = gameStateService.initBoardData();
      initialState.chanceCards = gameStateService.initChanceCards();
      
      // 重置游戏状态
      this.gameState = initialState;
      
      // 显示重新开始消息
      this.showEventMessage(
        '游戏重新开始', 
        '准备好开始新的冒险了吗？', 
        [{ text: '开始游戏', action: 'confirm' }]
      );
    }
  }
};
</script>

<style scoped>
.monopoly-game {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.game-container {
  width: 100%;
  max-width: 1200px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
  padding: 20px;
  position: relative;
}

.game-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.game-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.nav-actions {
  display: flex;
  align-items: center;
}

.game-status {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.round-info {
  font-size: 18px;
  font-weight: bold;
}

.game-over {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #e53935;
}
</style>